package com.hjm.security.handler;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.hjm.common.core.domain.Result;
import com.hjm.common.core.enums.ResultCode;
import com.hjm.security.exception.ServiceException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.context.support.DefaultMessageSourceResolvable;

import java.util.Collection;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/*   全局异常处理 ：不在 oj-system 启动类的 scope 范围内，需要加上*/

    /**
     * 请求⽅式不⽀持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<?>
    handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        e.printStackTrace();
        return Result.fail(ResultCode.ERROR);
    }

    /**
     * 拦截运⾏时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<?> handleRuntimeException(RuntimeException e, HttpServletRequest
            request) {
        String requestURI = request.getRequestURI();
        e.printStackTrace();

        return Result.fail(ResultCode.ERROR);
    }



    /*
    * 传入参数异常
    * validation 测试*/
    @ExceptionHandler(BindException.class)
    public Result<Void> handleBindException(BindException e) {
         log.error(e.getMessage());
         String message = join(e.getAllErrors(),DefaultMessageSourceResolvable::getDefaultMessage, ", ");
         return Result.fail(ResultCode.FAILED_PARAMS_VALIDATE.getCode(), message);
    }

    private <E> String join(Collection<E> collection, Function<E, String>
            function, CharSequence delimiter) {
         if (CollUtil.isEmpty(collection)) {
             return StrUtil.EMPTY;
         }
         return
                collection.stream().map(function).filter(Objects::nonNull).collect(Collectors.joining(delimiter));
    }


    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
    // log.error("请求地址'{}',发⽣异常.", requestURI, e);
        e.printStackTrace();

        return Result.fail(ResultCode.ERROR);
    }


    @ExceptionHandler(ServiceException.class)
    public Result<?> handleServiceException(ServiceException e, HttpServletRequest request) {
        log.error("请求地址'{}',发⽣异常.", request.getRequestURI());
        e.printStackTrace();
        return Result.fail( e.getMessage());
    }


}
